<template>
  <div class="riders-container">
    <el-card class="riders-card">
      <template #header>
        <div class="card-header">
          <h2>骑手管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddRider" :icon="Plus">添加骑手</el-button>
            <el-button @click="refreshRiders" :icon="Refresh">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 骑手状态统计 -->
      <div class="status-cards">
        <el-card class="status-card" shadow="hover">
          <div class="status-icon online">
            <el-icon><UserFilled /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-value">{{ onlineRidersCount }}</div>
            <div class="status-label">在线骑手</div>
          </div>
        </el-card>
        <el-card class="status-card" shadow="hover">
          <div class="status-icon available">
            <el-icon><Bicycle /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-value">{{ availableRidersCount }}</div>
            <div class="status-label">可用骑手</div>
          </div>
        </el-card>
        <el-card class="status-card" shadow="hover">
          <div class="status-icon busy">
            <el-icon><Loading /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-value">{{ busyRidersCount }}</div>
            <div class="status-label">忙碌骑手</div>
          </div>
        </el-card>
        <el-card class="status-card" shadow="hover">
          <div class="status-icon offline">
            <el-icon><MuteNotification /></el-icon>
          </div>
          <div class="status-info">
            <div class="status-value">{{ offlineRidersCount }}</div>
            <div class="status-label">离线骑手</div>
          </div>
        </el-card>
      </div>

      <!-- 骑手筛选 -->
      <div class="filter-section">
        <el-form :inline="true" :model="filterForm" class="filter-form">
          <el-form-item label="骑手姓名">
            <el-input v-model="filterForm.name" placeholder="输入骑手姓名" clearable />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="filterForm.phone" placeholder="输入联系电话" clearable />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="filterForm.status" placeholder="选择状态" clearable>
              <el-option label="离线" :value="0" />
              <el-option label="空闲" :value="1" />
              <el-option label="忙碌" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
            <el-button @click="resetFilter" :icon="Delete">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 骑手列表 -->
      <el-table :data="ridersList" style="width: 100%" v-loading="loading" border stripe>
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="骑手姓名" min-width="120">
          <template #default="scope">
            <div class="rider-name">
              <el-avatar :size="32" :icon="UserFilled" />
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" min-width="120" />
        <el-table-column prop="vehicleType" label="交通工具" min-width="100">
          <template #default="scope">
            <el-tag size="small" effect="plain" type="info">
              {{ getVehicleTypeText(scope.row.vehicleType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getRiderStatusType(scope.row.status)" effect="light">
              {{ getRiderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前订单数" width="100">
          <template #default="scope">
            <div class="order-count">
              <el-badge :value="scope.row.currentOrderCount || 0" :max="10" type="primary" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="今日完成" width="100">
          <template #default="scope">
            <span>{{ scope.row.completedOrderCount || 0 }}单</span>
          </template>
        </el-table-column>
        <el-table-column label="平均配送时间" width="120">
          <template #default="scope">
            <span>{{ scope.row.avgDeliveryTime || 0 }}分钟</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="small" @click="viewRiderDetail(scope.row)" :icon="View">详情</el-button>
              <el-button type="success" size="small" @click="handleUpdateStatus(scope.row, 1)" 
                :disabled="scope.row.status === 1"
                v-if="scope.row.status !== 0">设为空闲</el-button>
              <el-button type="warning" size="small" @click="handleUpdateStatus(scope.row, 2)" 
                :disabled="scope.row.status === 2"
                v-if="scope.row.status !== 0">设为忙碌</el-button>
              <el-button type="info" size="small" @click="handleUpdateStatus(scope.row, 0)" 
                :disabled="scope.row.status === 0">设为离线</el-button>
              <el-button type="danger" size="small" @click="handleDeleteRider(scope.row)" :icon="Delete">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑骑手对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加骑手' : '编辑骑手'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="riderForm" :rules="riderRules" ref="riderFormRef" label-width="100px">
        <el-form-item label="骑手姓名" prop="name">
          <el-input v-model="riderForm.name" placeholder="请输入骑手姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="riderForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="交通工具" prop="vehicleType">
          <el-select v-model="riderForm.vehicleType" placeholder="请选择交通工具">
            <el-option label="电动车" value="electric_bike" />
            <el-option label="摩托车" value="motorcycle" />
            <el-option label="自行车" value="bicycle" />
            <el-option label="步行" value="walk" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="riderForm.status" placeholder="请选择状态">
            <el-option label="离线" :value="0" />
            <el-option label="空闲" :value="1" />
            <el-option label="忙碌" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRiderForm" :loading="submitLoading">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { getRiders, updateRiderStatus, deleteRider, addRider, updateRider } from '@/api/riders';
import {
  UserFilled,
  Bicycle,
  Loading,
  MuteNotification,
  Search,
  Delete,
  View,
  Plus,
  Refresh
} from '@element-plus/icons-vue';

const router = useRouter();

// 骑手列表数据
const ridersList = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 统计数据
const onlineRidersCount = computed(() => {
  return ridersList.value.filter(rider => rider.status !== 0).length;
});

const availableRidersCount = computed(() => {
  return ridersList.value.filter(rider => rider.status === 1).length;
});

const busyRidersCount = computed(() => {
  return ridersList.value.filter(rider => rider.status === 2).length;
});

const offlineRidersCount = computed(() => {
  return ridersList.value.filter(rider => rider.status === 0).length;
});

// 筛选表单
const filterForm = reactive({
  name: '',
  phone: '',
  status: ''
});

// 骑手表单
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const submitLoading = ref(false);
const riderFormRef = ref(null);
const riderForm = reactive({
  id: null,
  name: '',
  phone: '',
  vehicleType: 'electric_bike',
  status: 1
});

const riderRules = {
  name: [
    { required: true, message: '请输入骑手姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  vehicleType: [
    { required: true, message: '请选择交通工具', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
};

// 获取骑手列表
const fetchRiders = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      name: filterForm.name || null,
      phone: filterForm.phone || null
    };
    
    const res = await getRiders(params);
    if (res.code === 200) {
      ridersList.value = res.data.items || [];
      total.value = res.data ? res.data.total : 0;
    } else {
      ElMessage.error(res.msg || '获取骑手列表失败');
    }
  } catch (error) {
    console.error('获取骑手列表失败:', error);
    ElMessage.error('获取骑手列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新骑手列表
const refreshRiders = () => {
  fetchRiders();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchRiders();
};

// 重置筛选
const resetFilter = () => {
  filterForm.name = '';
  filterForm.phone = '';
  filterForm.status = '';
  currentPage.value = 1;
  fetchRiders();
};

// 查看骑手详情
const viewRiderDetail = (rider) => {
  router.push(`/home/riders/detail/${rider.id}`);
};

// 添加骑手
const handleAddRider = () => {
  dialogType.value = 'add';
  riderForm.id = null;
  riderForm.name = '';
  riderForm.phone = '';
  riderForm.vehicleType = 'electric_bike';
  riderForm.status = 1;
  dialogVisible.value = true;
};

// 更新骑手状态
const handleUpdateStatus = async (rider, status) => {
  try {
    const res = await updateRiderStatus(rider.id, status);
    if (res.code === 200) {
      ElMessage.success('状态更新成功');
      // 更新本地数据
      const index = ridersList.value.findIndex(item => item.id === rider.id);
      if (index !== -1) {
        ridersList.value[index].status = status;
      }
    } else {
      ElMessage.error(res.msg || '状态更新失败');
    }
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  }
};

// 删除骑手
const handleDeleteRider = (rider) => {
  ElMessageBox.confirm(`确定要删除骑手 ${rider.name} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteRider(rider.id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        fetchRiders(); // 重新获取列表
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

// 提交骑手表单
const submitRiderForm = async () => {
  if (!riderFormRef.value) return;
  
  await riderFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    submitLoading.value = true;
    try {
      let res;
      if (dialogType.value === 'add') {
        res = await addRider(riderForm);
      } else {
        res = await updateRider(riderForm);
      }
      
      if (res.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功');
        dialogVisible.value = false;
        fetchRiders(); // 重新获取列表
      } else {
        ElMessage.error(res.msg || (dialogType.value === 'add' ? '添加失败' : '编辑失败'));
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error('提交失败');
    } finally {
      submitLoading.value = false;
    }
  });
};

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchRiders();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchRiders();
};

// 获取骑手状态文本
const getRiderStatusText = (status) => {
  const statusMap = {
    0: '离线',
    1: '空闲',
    2: '忙碌'
  };
  return statusMap[status] || '未知';
};

// 获取骑手状态类型
const getRiderStatusType = (status) => {
  const statusMap = {
    0: 'info',
    1: 'success',
    2: 'warning'
  };
  return statusMap[status] || 'info';
};

// 获取交通工具文本
const getVehicleTypeText = (vehicleType) => {
  const vehicleTypeMap = {
    'electric_bike': '电动车',
    'motorcycle': '摩托车',
    'bicycle': '自行车',
    'walk': '步行'
  };
  return vehicleTypeMap[vehicleType] || vehicleType;
};

onMounted(() => {
  fetchRiders();
});
</script>

<style scoped>
.riders-container {
  padding: 20px;
}

.riders-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 状态卡片样式 */
.status-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.status-card {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s;
}

.status-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.status-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.status-icon .el-icon {
  font-size: 24px;
  color: white;
}

.status-icon.online {
  background-color: #67c23a;
}

.status-icon.available {
  background-color: #409eff;
}

.status-icon.busy {
  background-color: #e6a23c;
}

.status-icon.offline {
  background-color: #909399;
}

.status-info {
  display: flex;
  flex-direction: column;
}

.status-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

/* 筛选表单样式 */
.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

/* 骑手列表样式 */
.rider-name {
  display: flex;
  align-items: center;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 订单数量样式 */
.order-count {
  display: flex;
  justify-content: center;
}

/* 对话框样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 